package daos;

import java.util.ArrayList;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import entidades.Evento;

public class EventoDAO {
	private Session sesion;
	private Transaction tx;

	public Integer guardaEvento(Evento evento) throws HibernateException {
		Integer id = 0;

		try {
			iniciaOperacion();
			id = (Integer) sesion.save(evento);
			tx.commit();
		} catch (HibernateException he) {
			manejaExcepcion(he);
			throw he;
		} finally {
			sesion.close();
		}

		return id;
	}

	public void actualizaEvento(Evento evento) throws HibernateException {
		try {
			iniciaOperacion();
			sesion.update(evento);
			tx.commit();
		} catch (HibernateException he) {
			manejaExcepcion(he);
			throw he;
		} finally {
			sesion.close();
		}
	}

	public void eliminaEvento(Evento evento) throws HibernateException {
		try {
			iniciaOperacion();
			sesion.delete(evento);
			tx.commit();
		} catch (HibernateException he) {
			manejaExcepcion(he);
			throw he;
		} finally {
			sesion.close();
		}
	}

	public Evento obtenEvento(Integer idEvento) throws HibernateException {
		Evento evento = null;
		try {
			iniciaOperacion();
			evento = (Evento) sesion.get(Evento.class, idEvento);
		} finally {
			sesion.close();
		}

		return evento;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Evento> obtenListaEventos() throws HibernateException {
		ArrayList<Evento> listaEventos = new ArrayList<Evento>();

		try {
			iniciaOperacion();
			listaEventos = new ArrayList<Evento>(sesion.createQuery("from Evento").list());
		} finally {
			sesion.close();
		}

		return listaEventos;
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<Evento> consultarEvento(String s) throws HibernateException {
		ArrayList<Evento> listaEventos = new ArrayList<Evento>();

		try {
			iniciaOperacion();
			Query q = sesion.createSQLQuery("SELECT * FROM evento WHERE descripcion LIKE :string or lugar LIKE :string").addEntity(Evento.class);
//			Query q = sesion.createQuery("from Material as m where m.descripcion = :string");
			q.setParameter("string", "%"+ s+"%");
			
			listaEventos = new ArrayList<Evento>(q.list());
		} finally {
			sesion.close();
		}

		return listaEventos;
	}

	private void iniciaOperacion() throws HibernateException {
		sesion = HibernateUtil.getSessionFactory().openSession();
		tx = sesion.beginTransaction();
	}

	private void manejaExcepcion(HibernateException he)
			throws HibernateException {
		tx.rollback();
		throw new HibernateException(
				"Ocurrió un error en la capa de acceso a datos", he);
	}

}
